package com.nd.qa.shareplate.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import com.gargoylesoftware.htmlunit.Page;
import com.nd.qa.shareplate.common.SessionUserInfo;
import com.nd.qa.shareplate.common.SysConstant;
import com.nd.qa.shareplate.model.ElementExpectType;
import com.nd.qa.shareplate.model.ExpectType;
import com.nd.qa.shareplate.model.OperatorLog;
import com.nd.qa.shareplate.model.PageElement;
import com.nd.qa.shareplate.model.SharePage;
import com.nd.qa.shareplate.service.ElementExpectTypeService;
import com.nd.qa.shareplate.service.ExpectTypeService;
import com.nd.qa.shareplate.service.OperatorLogService;
import com.nd.qa.shareplate.service.PageElementService;
import com.nd.qa.shareplate.service.PageService;
import com.nd.qa.shareplate.util.FormatTimeUtil;
import com.nd.qa.shareplate.util.JsonUtil;


/**
 * <p>脚本模块控制类</p>
 * @author huangjian
 * @createDate 2015-09-17 下午 12:36:21
 * @version V1.0
 */

@Controller("com.nd.qa.shareplate.controller.ElementController")
@RequestMapping("/element/*")
public class ElementController {

	Logger logger = LoggerFactory.getLogger(ElementController.class);
	
	@Autowired
	@Qualifier("com.nd.qa.shareplate.service.PageElementService")
	private PageElementService elementService;
	
	@Autowired
	@Qualifier("com.nd.qa.shareplate.service.PageService")
	private PageService pageService;
	
	@Autowired
	@Qualifier("com.nd.qa.shareplate.service.ElementExpectTypeService")
	private ElementExpectTypeService expectTypeService;
	
	@Autowired
	@Qualifier("com.nd.qa.shareplate.service.OperatorLogService")
	private OperatorLogService operatorLogService;
	
	@Autowired
	@Qualifier("com.nd.qa.shareplate.service.ExpectTypeService")
	private ExpectTypeService expectService;
	
	/**
	 * 查询元素类型和操作类型信息
	 * @param request
	 * @param response
	 * @param params
	 */
	@RequestMapping("/queryElementType")
	public void queryElementType(HttpServletRequest request,HttpServletResponse response,@RequestBody String params){
		
		HashMap<String, Object> resultMap = new HashMap<String,Object>();
		
		try {
			HashMap<String, Object> inParam = JsonUtil.toObject(params, HashMap.class);
			String testType = String.valueOf(inParam.get("testType"));
			Map<String, Object> map = new HashMap<String, Object>();
			if ("3".equals(testType)||"4".equals(testType)) {//macaca测试
				map.put("elementExpectFlag", "1");
			}else{
				map.put("elementExpectFlag", "0");
			}
			List<HashMap<String, Object>> elTypeList = elementService.queryElementType();
			List<HashMap<String, Object>> elActionList = elementService.queryElementAction();
			List<ElementExpectType>       elExpectList = expectTypeService.queryElementExpectType(map);
			//获取校验类型
			ExpectType expectType = new ExpectType();
			List<ExpectType> expectTypes = expectService.queryExpectType(expectType);
			resultMap.put("code", "0");
			resultMap.put("message", "查询元素类型成功");
			resultMap.put("elTypeList", elTypeList);
			resultMap.put("elActionList", elActionList);
			resultMap.put("elExpectList", elExpectList);
			resultMap.put("expectTypes", expectTypes);
			response.setCharacterEncoding("UTF-8");
			response.setContentType("text/html;charset=UTF-8");
		    response.getWriter().print(JsonUtil.toString(resultMap));
		} catch (Exception e) {
			logger.error("查询元素类型异常："+e.toString());
			e.printStackTrace();
		}
	}
	/**
	 * 查询page下的所有元素，并展示
	 * @param request
	 * @param response
	 * @param params
	 * @param model
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/showElements")
	public String showElements(HttpServletRequest request,HttpServletResponse response,@RequestBody String params,HttpSession session,Model model){
		
		SessionUserInfo sessionUserInfo = (SessionUserInfo) session.getAttribute(SysConstant.SESSION_KEY_LOGIN_USER);
		HashMap<String, Object> resultMap = new HashMap<String,Object>();
		if (sessionUserInfo==null) {
			resultMap.put("code", "-2");
			resultMap.put("message", "您还未登录");
		}
		HashMap<String, Object> inParam = JsonUtil.toObject(params, HashMap.class);
		String pageId = String.valueOf(inParam.get("pageId"));
		PageElement pageElement = new PageElement();
		//定义分页的参数
		Integer cpage = Integer.valueOf(String.valueOf(inParam.get("cpage")));//当前页面
		Integer pageSize = Integer.valueOf(String.valueOf(inParam.get("pageSize")));//默认每页展示的记录数
		Integer startIndex = (cpage-1)*pageSize;
		Integer totalPages = 0;
		//查询记录入参
		HashMap<String, Object> paramMap = new HashMap<String,Object>();
		try {
			//查询所有元素信息记录
			pageElement.setPageId(Integer.valueOf(pageId));
			List<HashMap<String, Object>> totalList = elementService.queryElementById(pageElement);
			if (totalList.size()%pageSize==0) {
				totalPages = totalList.size()/pageSize;
			}else{
				totalPages = totalList.size()/pageSize+1;
			}
			paramMap.put("startIndex", startIndex);
			paramMap.put("pageSize", pageSize);
			paramMap.put("pageId", Integer.valueOf(pageId));
			List<HashMap<String, Object>> elementList = elementService.queryLimitElement(paramMap);
			model.addAttribute("elementList", elementList);
			model.addAttribute("totalPages", totalPages);
		} catch (Exception e) {
			logger.error("查询页面元素异常："+e.toString());
			e.printStackTrace();
		}
		return "/main/showelement";
	}
	/**
	 * 添加新的元素信息
	 * @param request
	 * @param response
	 * @param params
	 * @param session
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/addElement")
	public void addElement(HttpServletRequest request,HttpServletResponse response,@RequestBody String params,HttpSession session){
		
		SessionUserInfo sessionUserInfo = (SessionUserInfo) session.getAttribute(SysConstant.SESSION_KEY_LOGIN_USER);
		HashMap<String, Object> resultMap = new HashMap<String,Object>();
		if (sessionUserInfo==null) {
			resultMap.put("code", "-2"); 
			resultMap.put("message", "您还未登录");
		}
		HashMap<String, Object> inParam = JsonUtil.toObject(params, HashMap.class);
		PageElement pageElement = new PageElement();
		//获取入参
		Integer	elementOrder = 0;
		Integer	elementDrag = 0;
		Integer pageId = Integer.valueOf(String.valueOf(inParam.get("pageId")));
		String	elementTypeId = String.valueOf(inParam.get("elementTypeId"));
		String	elementTypeName = "";
		if (elementTypeId!=null&&!"".equals(elementTypeId)&&!"null".equals(elementTypeId)) {
			elementTypeName = String.valueOf(inParam.get("elementTypeName"));
		}
		String	elementContent = String.valueOf(inParam.get("elementContent"));
		if (elementContent!=null) {
			elementContent = elementContent.replaceAll("\"","\'");  
		}
		String	elementExpectName = String.valueOf(inParam.get("elementExpectName"));
		String	elementExpectType = String.valueOf(inParam.get("elementExpectType"));
		String	elementExpectContent = String.valueOf(inParam.get("elementExpectContent"));
		String	elementExpectOrder = String.valueOf(inParam.get("elementExpectOrder"));
		if (elementExpectOrder==null||"".equals(elementExpectOrder)) {
			elementExpectOrder = "0";
		}
		String	elementWaitTime = String.valueOf(inParam.get("elementWaitTime"));
		if (elementWaitTime==null||"".equals(elementWaitTime)) {
			elementWaitTime = "0";
		}
		String	elementExpectResult = String.valueOf(inParam.get("elementExpectResult"));
		String  elementOperateDesc = String.valueOf(inParam.get("elementOperateDesc"));
		if (inParam.get("elementOrder")!=null&&!"".equals(inParam.get("elementOrder"))) {
			elementOrder = Integer.valueOf(String.valueOf(inParam.get("elementOrder")));
		}
		String	elementActionId = String.valueOf(inParam.get("elementActionId"));
		String	elementText = String.valueOf(inParam.get("elementText"));
		String	elementTextFlag = String.valueOf(inParam.get("elementTextFlag"));
		if (inParam.get("elementDrag")!=null&&!"".equals(inParam.get("elementDrag"))) {
			elementDrag = Integer.valueOf(String.valueOf(inParam.get("elementDrag")));
		}
		String	elementPrecious = String.valueOf(inParam.get("elementPrecious"));
		if (elementPrecious!=null&&!"".equals(elementPrecious)) {
			pageElement.setElementPreciousId(Integer.valueOf(elementPrecious));
		}else{
			pageElement.setElementPreciousId(0);
		}
		String	isIFrameFlag = String.valueOf(inParam.get("isIFrameFlag"));
		String	isSwitchPage = String.valueOf(inParam.get("isSwitchPage"));
		Integer	focusTypeId = null;
		String	focusTypeName = null;
		if (inParam.get("focusTypeId")!=null&&String.valueOf(inParam.get("focusTypeId")).length()>0) {//聚焦控件操作
			focusTypeId = Integer.valueOf(String.valueOf(inParam.get("focusTypeId")));
			focusTypeName = String.valueOf(inParam.get("focusTypeName"));
		}
		String	overIFrameFlag = String.valueOf(inParam.get("overIFrameFlag"));
		String	iFrameElementType = String.valueOf(inParam.get("iFrameElementType"));
		String	iFrameElementContent = String.valueOf(inParam.get("iFrameElementContent"));
		
		pageElement.setPageId(pageId);
		//单纯验证的情况
		if (elementTypeId!=null&&!"".equals(elementTypeId)&&!"null".equals(elementTypeId)) {
			pageElement.setElementTypeId(Integer.valueOf(elementTypeId));
		}
		pageElement.setElementTypeName(elementTypeName);
		pageElement.setElementContent(elementContent);
		pageElement.setElementOrder(elementOrder);
		if (elementActionId!=null&&!"".equals(elementActionId)&&!"null".equals(elementActionId)) {
			pageElement.setElementActionId(Integer.valueOf(elementActionId));
		}
		pageElement.setElementText(elementText);
		pageElement.setElementTextFlag(elementTextFlag);
		pageElement.setDragCount(elementDrag);
		pageElement.setElementForPage("N");
		pageElement.setElementExpectName(elementExpectName);
		pageElement.setElementExpectType(elementExpectType);
		pageElement.setElementExpectContent(elementExpectContent);
		pageElement.setElementExpectOrder(Integer.valueOf(elementExpectOrder));
		pageElement.setElementWaitTime(Long.valueOf(elementWaitTime));
		pageElement.setElementExpectResult(elementExpectResult);
		pageElement.setElementOperateDesc(elementOperateDesc);//操作元素信息描述
		pageElement.setIsIframeFlag(isIFrameFlag);
		pageElement.setOverIframeFlag(overIFrameFlag);
		pageElement.setIframeElementType(iFrameElementType);
		pageElement.setIframeElementContent(iFrameElementContent);
		pageElement.setIsSwitchPage(isSwitchPage);
		pageElement.setFocusTypeId(focusTypeId);
		pageElement.setFocusTypeName(focusTypeName);
		pageElement.setStatus("A");
		try {
			//查询元素列表序列
			 Integer elementSeq = elementService.quertElmSeqByName("element_seq");
			 pageElement.setElementId(elementSeq);
			//添加新元素信息
			elementService.insertElememt(pageElement);
			//记录添加元素日志信息
			insertOperatorLog(sessionUserInfo.getUserId(), SysConstant.OPERATOR_ACTION_ADD_LOG, SysConstant.OPERATOR_TYPE_ELEMENT_LOG, -1, elementSeq);
			resultMap.put("code", "0");
			resultMap.put("message", "添加元素成功");
			response.setCharacterEncoding("UTF-8");
			response.setContentType("text/html;charset=UTF-8");
		    response.getWriter().print(JsonUtil.toString(resultMap));
		} catch (Exception e) {
			logger.error("添加元素异常："+e.toString());
			e.printStackTrace();
		}
	}
	/**
	 * 操作日志类
	 * @param userId
	 * @param operatorAction
	 * @param operatorType
	 */
	public void insertOperatorLog(String userId,String operatorAction,String operatorType,Integer pageId,Integer elementId){
		try {
			OperatorLog operatorLog = new OperatorLog();
			operatorLog.setUserId(userId);
			operatorLog.setOperatorAction(operatorAction);
			operatorLog.setOperatorType(operatorType);
			operatorLog.setPageId(pageId);
			operatorLog.setElementId(elementId);
			operatorLog.setCreateTime(FormatTimeUtil.dateToStrLong(new Date()));
			operatorLog.setStatus("A");
			operatorLogService.insertOperatorLog(operatorLog);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	/**
	 * 修改元素信息
	 * @param request
	 * @param response
	 * @param params
	 * @param session
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/modifyElement")
	public void modifyElement(HttpServletRequest request,HttpServletResponse response,@RequestBody String params,HttpSession session){
		
		SessionUserInfo sessionUserInfo = (SessionUserInfo) session.getAttribute(SysConstant.SESSION_KEY_LOGIN_USER);
		HashMap<String, Object> resultMap = new HashMap<String,Object>();
		if (sessionUserInfo==null) {
			resultMap.put("code", "-2");
			resultMap.put("message", "您还未登录");
		}
		HashMap<String, Object> inParam = JsonUtil.toObject(params, HashMap.class);
		PageElement pageElement = new PageElement();
		//获取入参
		Integer	elementOrder = 0;
		Integer	elementDrag = 0;
		Integer pageId = Integer.valueOf(String.valueOf(inParam.get("pageId")));
		Integer elementId = Integer.valueOf(String.valueOf(inParam.get("elementId")));
		String	elementTypeId = String.valueOf(inParam.get("elementTypeId"));
		String	elementTypeName = String.valueOf(inParam.get("elementTypeName"));
		String	elementContent = String.valueOf(inParam.get("elementContent"));
		String	elementExpectName = String.valueOf(inParam.get("elementExpectName"));
		String	elementExpectType = String.valueOf(inParam.get("elementExpectType"));
		String	elementExpectContent = String.valueOf(inParam.get("elementExpectContent"));
		String	elementExpectOrder = String.valueOf(inParam.get("elementExpectOrder"));
		if (elementExpectOrder==null||"".equals(elementExpectOrder)) {
			elementExpectOrder = "0";
		}
		String	elementExpectResult = String.valueOf(inParam.get("elementExpectResult"));
		String	elementOperateDesc = String.valueOf(inParam.get("elementOperateDesc"));
		if (inParam.get("elementOrder")!=null&&!"".equals(inParam.get("elementOrder"))) {
			elementOrder = Integer.valueOf(String.valueOf(inParam.get("elementOrder")));
		}
		String	elementActionId = String.valueOf(inParam.get("elementActionId"));
		String	elementText = String.valueOf(inParam.get("elementText"));
		String	elementTextFlag = String.valueOf(inParam.get("elementTextFlag"));
		if (inParam.get("elementDrag")!=null&&!"".equals(inParam.get("elementDrag"))) {
			elementDrag = Integer.valueOf(String.valueOf(inParam.get("elementDrag")));
		}
		String	elementPrecious = String.valueOf(inParam.get("elementPrecious"));
		if (elementPrecious!=null&&!"".equals(elementPrecious)) {
			pageElement.setElementPreciousId(Integer.valueOf(elementPrecious));
		}else {
			pageElement.setElementPreciousId(0);
		}
		//iframe的选择
		String	isIFrameFlag = String.valueOf(inParam.get("isIFrameFlag"));
		String	elementWaitTime = String.valueOf(inParam.get("elementWaitTime"));
		if (elementWaitTime!=null&&!"".equals(elementWaitTime)) {
			pageElement.setElementWaitTime(Long.valueOf(elementWaitTime));
		}else {
			pageElement.setElementWaitTime(0);
		}
		String	isSwitchPage = String.valueOf(inParam.get("isSwitchPage"));
		Integer	focusTypeId = null;
		String	focusTypeName = null;
		if (inParam.get("focusTypeId")!=null&&String.valueOf(inParam.get("focusTypeId")).length()>0) {
			focusTypeId = Integer.valueOf(String.valueOf(inParam.get("focusTypeId")));
			focusTypeName = String.valueOf(inParam.get("focusTypeName"));
		}
		String	overIFrameFlag = String.valueOf(inParam.get("overIFrameFlag"));
		String	iFrameElementType = String.valueOf(inParam.get("iFrameElementType"));
		String	iFrameElementContent = String.valueOf(inParam.get("iFrameElementContent"));
		pageElement.setPageId(pageId);
		pageElement.setElementTypeId(Integer.valueOf(elementTypeId));
		pageElement.setElementTypeName(elementTypeName);
		pageElement.setElementContent(elementContent);
		pageElement.setElementOrder(elementOrder);
		pageElement.setElementActionId(Integer.valueOf(elementActionId));
		pageElement.setElementText(elementText);
		pageElement.setElementTextFlag(elementTextFlag);
		pageElement.setDragCount(elementDrag);
		pageElement.setElementId(elementId);
		pageElement.setElementExpectName(elementExpectName);
		pageElement.setElementExpectType(elementExpectType);
		pageElement.setElementExpectContent(elementExpectContent);
		pageElement.setElementExpectOrder(Integer.valueOf(elementExpectOrder));
		pageElement.setElementExpectResult(elementExpectResult);
		pageElement.setElementOperateDesc(elementOperateDesc);
		pageElement.setIsIframeFlag(isIFrameFlag);
		pageElement.setOverIframeFlag(overIFrameFlag);
		pageElement.setIframeElementType(iFrameElementType);
		pageElement.setIframeElementContent(iFrameElementContent);
		pageElement.setIsSwitchPage(isSwitchPage);
		pageElement.setFocusTypeId(focusTypeId);
		pageElement.setFocusTypeName(focusTypeName);
		try {
			//添加新元素信息
			elementService.updateElement(pageElement);
			//记录修改元素信息日志
			insertOperatorLog(sessionUserInfo.getUserId(), SysConstant.OPERATOR_ACTION_UPDATE_LOG, SysConstant.OPERATOR_TYPE_ELEMENT_LOG, -1, elementId);
			resultMap.put("code", "0");
			resultMap.put("message", "修改元素成功");
			response.setCharacterEncoding("UTF-8");
			response.setContentType("text/html;charset=UTF-8");
		    response.getWriter().print(JsonUtil.toString(resultMap));
		} catch (Exception e) {
			logger.error("修改元素异常："+e.toString());
			e.printStackTrace();
		}
	}
	
	/**
	 * 插入新的元素信息
	 * @param request
	 * @param response
	 * @param params
	 * @param session
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/insertElement")
	public void insertElement(HttpServletRequest request,HttpServletResponse response,@RequestBody String params,HttpSession session){
		
		SessionUserInfo sessionUserInfo = (SessionUserInfo) session.getAttribute(SysConstant.SESSION_KEY_LOGIN_USER);
		HashMap<String, Object> resultMap = new HashMap<String,Object>();
		if (sessionUserInfo==null) {
			resultMap.put("code", "-2"); 
			resultMap.put("message", "您还未登录");
		}
		HashMap<String, Object> inParam = JsonUtil.toObject(params, HashMap.class);
		PageElement pageElement = new PageElement();
		//获取入参
		Integer	elementOrder = 0;
		Integer	elementDrag = 0;
		Integer pageId = Integer.valueOf(String.valueOf(inParam.get("pageId")));
		String	elementTypeId = String.valueOf(inParam.get("elementTypeId"));
		String	elementTypeName = "";
		if (elementTypeId!=null&&!"".equals(elementTypeId)&&!"null".equals(elementTypeId)) {
			elementTypeName = String.valueOf(inParam.get("elementTypeName"));
		}
		String	elementContent = String.valueOf(inParam.get("elementContent"));
		if (elementContent!=null) {
			elementContent = elementContent.replaceAll("\"","\'");  
		}
		String	elementExpectName = String.valueOf(inParam.get("elementExpectName"));
		String	elementExpectType = String.valueOf(inParam.get("elementExpectType"));
		String	elementExpectContent = String.valueOf(inParam.get("elementExpectContent"));
		String	elementExpectOrder = String.valueOf(inParam.get("elementExpectOrder"));
		if (elementExpectOrder==null||"".equals(elementExpectOrder)) {
			elementExpectOrder = "0";
		}
		String	elementWaitTime = String.valueOf(inParam.get("elementWaitTime"));
		if (elementWaitTime==null||"".equals(elementWaitTime)) {
			elementWaitTime = "0";
		}
		String	elementExpectResult = String.valueOf(inParam.get("elementExpectResult"));
		String  elementOperateDesc = String.valueOf(inParam.get("elementOperateDesc"));
		if (inParam.get("elementOrder")!=null&&!"".equals(inParam.get("elementOrder"))) {
			elementOrder = Integer.valueOf(String.valueOf(inParam.get("elementOrder")));
		}
		String	elementActionId = String.valueOf(inParam.get("elementActionId"));
		String	elementText = String.valueOf(inParam.get("elementText"));
		String	elementTextFlag = String.valueOf(inParam.get("elementTextFlag"));
		if (inParam.get("elementDrag")!=null&&!"".equals(inParam.get("elementDrag"))) {
			elementDrag = Integer.valueOf(String.valueOf(inParam.get("elementDrag")));
		}
		String	elementPrecious = String.valueOf(inParam.get("elementPrecious"));//前置元素
		String	elementAfter = String.valueOf(inParam.get("elementAfter"));//后置元素
		if (elementPrecious!=null&&!"".equals(elementPrecious)) {
			pageElement.setElementPreciousId(Integer.valueOf(elementPrecious));
		}else{
			pageElement.setElementPreciousId(0);
		}
		String	isIFrameFlag = String.valueOf(inParam.get("isIFrameFlag"));
		String	isSwitchPage = String.valueOf(inParam.get("isSwitchPage"));
		Integer	focusTypeId = null;
		String	focusTypeName = null;
		if (inParam.get("focusTypeId")!=null&&String.valueOf(inParam.get("focusTypeId")).length()>0) {//聚焦控件操作
			focusTypeId = Integer.valueOf(String.valueOf(inParam.get("focusTypeId")));
			focusTypeName = String.valueOf(inParam.get("focusTypeName"));
		}
		String	overIFrameFlag = String.valueOf(inParam.get("overIFrameFlag"));
		String	iFrameElementType = String.valueOf(inParam.get("iFrameElementType"));
		String	iFrameElementContent = String.valueOf(inParam.get("iFrameElementContent"));
		
		pageElement.setPageId(pageId);
		//单纯验证的情况
		if (elementTypeId!=null&&!"".equals(elementTypeId)&&!"null".equals(elementTypeId)) {
			pageElement.setElementTypeId(Integer.valueOf(elementTypeId));
		}
		pageElement.setElementTypeName(elementTypeName);
		pageElement.setElementContent(elementContent);
		pageElement.setElementOrder(elementOrder);
		if (elementActionId!=null&&!"".equals(elementActionId)&&!"null".equals(elementActionId)) {
			pageElement.setElementActionId(Integer.valueOf(elementActionId));
		}
		pageElement.setElementText(elementText);
		pageElement.setElementTextFlag(elementTextFlag);
		pageElement.setDragCount(elementDrag);
		pageElement.setElementForPage("N");
		pageElement.setElementExpectName(elementExpectName);
		pageElement.setElementExpectType(elementExpectType);
		pageElement.setElementExpectContent(elementExpectContent);
		pageElement.setElementExpectOrder(Integer.valueOf(elementExpectOrder));
		pageElement.setElementWaitTime(Long.valueOf(elementWaitTime));
		pageElement.setElementExpectResult(elementExpectResult);
		pageElement.setElementOperateDesc(elementOperateDesc);//操作元素信息描述
		pageElement.setIsIframeFlag(isIFrameFlag);
		pageElement.setOverIframeFlag(overIFrameFlag);
		pageElement.setIframeElementType(iFrameElementType);
		pageElement.setIframeElementContent(iFrameElementContent);
		pageElement.setIsSwitchPage(isSwitchPage);
		pageElement.setFocusTypeId(focusTypeId);
		pageElement.setFocusTypeName(focusTypeName);
		pageElement.setStatus("A");
		try {
			//查询元素列表序列
			 Integer elementSeq = elementService.quertElmSeqByName("element_seq");
			 pageElement.setElementId(elementSeq);
			//插入新元素信息
			elementService.insertElememt(pageElement);
			//操作该元素的前置元素和后置元素的信息
			//1.查询前置元素是否存在 
			PageElement pElements = new PageElement();
			pElements.setElementId(Integer.valueOf(elementAfter));
			PageElement aftElement = elementService.queryElementInfoByElemId(pElements);
			//2.修改前置元素的信息
			if (aftElement!=null) {
				pElements.setElementPreciousId(elementSeq);
				pElements.setElementTypeId(Integer.valueOf(elementTypeId));
				elementService.updateElement(pElements);
				//记录添加元素日志信息
				insertOperatorLog(sessionUserInfo.getUserId(), SysConstant.OPERATOR_ACTION_ADD_LOG, SysConstant.OPERATOR_TYPE_ELEMENT_LOG, -1, elementSeq);
				resultMap.put("code", "0");
				resultMap.put("message", "插入元素成功");
			}else{
				resultMap.put("code", "-1");
				resultMap.put("message", "插入元素失败");
			}
			response.setCharacterEncoding("UTF-8");
			response.setContentType("text/html;charset=UTF-8");
		    response.getWriter().print(JsonUtil.toString(resultMap));
		} catch (Exception e) {
			logger.error("插入元素异常："+e.toString());
			e.printStackTrace();
		}
	}
	/**
	 * 删除元素信息
	 * @param request
	 * @param response
	 * @param params
	 * @param session
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/delElement")
	public void delElement(HttpServletRequest request,HttpServletResponse response,@RequestBody String params,HttpSession session){
		
		SessionUserInfo sessionUserInfo = (SessionUserInfo) session.getAttribute(SysConstant.SESSION_KEY_LOGIN_USER);
		try {
			HashMap<String, Object> resultMap = new HashMap<String,Object>();
			if (sessionUserInfo==null) {
				resultMap.put("code", "-1");
				resultMap.put("message", "您还未登录");
				response.getWriter().print(JsonUtil.toString(resultMap));
			}
			HashMap<String, Object> inParam = JsonUtil.toObject(params, HashMap.class);
			//获取入参
			//List<HashMap<String, Object>> elements = (List<HashMap<String, Object>>)inParam.get("elements");
			PageElement pageElement = new PageElement();
			//for (int i = 0; i < elements.size(); i++) {
				//HashMap<String, Object> elementMap = elements.get(i);
				pageElement.setPageId(Integer.valueOf(String.valueOf(inParam.get("pageId"))));
				Integer elementId = Integer.valueOf(String.valueOf(inParam.get("elementId")));
				pageElement.setElementId(elementId);
				String elementForPage = String.valueOf(inParam.get("elementForPage"));
				//查询是否存在前置元素使用该元素的，是：则清空  
				
				if ("Y".equals(elementForPage)) {
					//删除页面信息
					//1.查询目标元素id为elementId的，此页面才是新增的页面
					SharePage sharePage = pageService.queryPageByElementId(elementId);
					deletePageById(String.valueOf(sharePage.getPageId()));
				}else{
					//删除元素信息,需要判断是否有子元素（以此元素作为前置元素的操作）
					elementService.deleteElement(pageElement);
				}
				//记录修改元素信息日志
				insertOperatorLog(sessionUserInfo.getUserId(), SysConstant.OPERATOR_ACTION_DEL_LOG, SysConstant.OPERATOR_TYPE_ELEMENT_LOG, -1, elementId);
			//}
			resultMap.put("code", "0");
			resultMap.put("message", "删除元素成功");
			response.setCharacterEncoding("UTF-8");
			response.setContentType("text/html;charset=UTF-8");
		    response.getWriter().print(JsonUtil.toString(resultMap));
		} catch (Exception e) {
			logger.error("删除元素异常："+e.toString());
			e.printStackTrace();
		}
	}
	/**
	 * 删除子元素信息
	 * @param elementId
	 */
	public void deletePageElement(Integer elementId){
		
		try {
			//查询子元素
			PageElement pageEle = elementService.queryChildElementById(elementId);
			if (pageEle!=null) {
				deletePageElement(pageEle.getElementId());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 删除页面
	 * @param request
	 * @param response
	 * @param session
	 * @param params
	 */

	public void deletePageById(String pageId){
		
		try {
			//根据pageId查询对应的moduleId
			SharePage page = pageService.queryPageById(Integer.valueOf(pageId));
			String moduleId = String.valueOf(page.getModuleId());
			PageElement pageElement = new PageElement();
			//1.删除该页面下的所有元素信息
			pageElement.setPageId(Integer.valueOf(pageId));
			elementService.deleteElement(pageElement);
			//2.查询要删除界面的父界面中元素的信息
			SharePage delPageInfo = pageService.queryPageById(Integer.valueOf(pageId));//查询该页面的信息
			PageElement pageElement2 = new PageElement();
			if (delPageInfo.getElementTargetId()!=0) {
				pageElement2.setElementId(delPageInfo.getElementTargetId());
				elementService.deleteElement(pageElement2);
			}
			//3.删除本身page
			//page对象重新生成
			SharePage pageSelf = new SharePage();
			pageSelf.setPageId(Integer.valueOf(pageId));
			pageService.deleteChildPages(pageSelf);
			//调用回调函数
			callBackDelPageInfo(moduleId, pageId);
		} catch (Exception e) {
			logger.error("删除页面异常："+e.toString());
			e.printStackTrace();
		}
	}
	/**
	 * 删除页面回调函数
	 * @param moduleId
	 * @param pageId
	 */
	public void callBackDelPageInfo(String moduleId,String pageId){
		
		try {
			SharePage page = new SharePage();
			//先删除pageId页面下的子页面以及子页面对应的元素，再删除本身页面
			//1。先查询该pageId下的所有子page信息
			page.setModuleId(Integer.valueOf(moduleId));
			page.setParentPageId(Integer.valueOf(pageId));
			List<HashMap<String, Object>> childPageList = pageService.queryChildPageList(page);
			//2.删除所有子page下的所有元素信息
			for (int i = 0; i < childPageList.size(); i++) {
				HashMap<String, Object> childPage = childPageList.get(i);
				//2.1 删除该子页面下的所有元素信息
				PageElement pageElement = new PageElement();
				pageElement.setPageId(Integer.valueOf(String.valueOf(childPage.get("page_id"))));
				elementService.deleteElement(pageElement);
				//2.2.查询要删除界面的父界面中元素的信息
				SharePage delPageInfo = pageService.queryPageById(Integer.valueOf(String.valueOf(childPage.get("page_id"))));
				PageElement pageElement2 = new PageElement();
				if (delPageInfo.getElementTargetId()!=0) {
					pageElement2.setElementId(delPageInfo.getElementTargetId());
					elementService.deleteElement(pageElement2);
				}
				//2.3 删除本身page    page对象重新生成
				SharePage pageSelf = new SharePage();
				pageSelf.setPageId(Integer.valueOf(String.valueOf(childPage.get("page_id"))));
				pageService.deleteChildPages(pageSelf);
				
				//如果还存在子页面，那么继续调用回调函数
				callBackDelPageInfo(moduleId,String.valueOf(childPage.get("page_id")));
			}
			
		} catch (Exception e) {
			logger.error("删除页面异常："+e.toString());
			e.printStackTrace();
		}
	}
	/**
	 * 查询元素信息
	 * @param request
	 * @param response
	 * @param params
	 * @param session
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/queryElementById")
	public void queryElementById(HttpServletRequest request,HttpServletResponse response,@RequestBody String params,HttpSession session){
		
		HashMap<String, Object> inParam = JsonUtil.toObject(params, HashMap.class);
		HashMap<String, Object> resultMap = new HashMap<String,Object>();
		PageElement pageElement = new PageElement();
		//获取入参
		Integer pageId = Integer.valueOf(String.valueOf(inParam.get("pageId")));
		if (inParam.get("elementId")!=null&&!"".equals(inParam.get("elementId"))) {
			Integer elementId = Integer.valueOf(String.valueOf(inParam.get("elementId")));
			pageElement.setElementId(elementId);
		}
		try {
			pageElement.setPageId(pageId);
			//查询元素信息
			List<HashMap<String, Object>> elementList = elementService.queryElementById(pageElement);
			resultMap.put("code", "0");
			resultMap.put("message", "查询元素成功");
			resultMap.put("elementList", elementList);
			response.setCharacterEncoding("UTF-8");
			response.setContentType("text/html;charset=UTF-8");
		    response.getWriter().print(JsonUtil.toString(resultMap));
		} catch (Exception e) {
			logger.error("查询元素异常："+e.toString());
			e.printStackTrace();
		}
	}
}
